package com.ww.nio.filechannel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用ByteBuffer实现文件拷贝
 * @author wanggw
 * 2023年10月17日 下午9:33:20
 */
public class NIOFileChannel01 {

	public static void main(String[] args) throws IOException {
		FileInputStream fileInputStream = new FileInputStream("D:/test01.txt");
		FileChannel fileChannel = fileInputStream.getChannel();
		
		FileOutputStream fileOutputStream = new FileOutputStream("D:/test02.txt");
		FileChannel fileChannel2 = fileOutputStream.getChannel();
		
		ByteBuffer byteBuffer = ByteBuffer.allocate(512);
		
		while (true) {
			
			/**
			 * 一定不要忘了
			 * 清空buffer
			 */
			byteBuffer.clear();
			
			int read = fileChannel.read(byteBuffer);
			if (-1 == read) {
				break;
			}
			// 将buffer中的数据写入fileChannel02
			// 一定要注意反转
			byteBuffer.flip();
			fileChannel2.write(byteBuffer);
		}
		
		/**
		 * 关闭相关资源
		 */
		fileInputStream.close();
		fileOutputStream.close();
	}
}
